<template>
  <div id="addRole">
    <h3>添加角色</h3>
    <!-- 角色信息 -->
    <Form :model="roleInfo" :rules="roleRule">
        <FormItem prop = "rolename" label="角色名称" >
            <Input v-model="roleInfo.rolename"></Input>
        </FormItem>
        <FormItem prop = "description" label="备注">
            <Input v-model="roleInfo.description"></Input>
        </FormItem>
    </Form>
    <h3>添加角色权限</h3>
    <!-- 权限树 -->
     <Tree ref="tree" :data="AllAuthority" show-checkbox></Tree>
    <Button type="primary" @click="saveRole()">提交</Button>
  </div>
</template>

<script>

export default {
  data(){
    return{
      roleInfo:{
        rolename:'',
        description:''
      }, //角色的基本信息
      AllAuthority:[], //角色的权限
      roleRule:{
        rolename:[
              { required: true, message: 'Please fill in the rolename', trigger: 'blur' }
        ],
        description:[
              { required: true, message: 'Please fill in the description', trigger: 'blur' }
        ]
      }
    }
  },
  created(){
    this.getauthority()
    
  },
  methods:{
    async getauthority(){
      const {data:res} = await this.$axios.get('/menu/menus')
      //将列表展开
      for(let item of res.data){
        item.expand = true
      }
      this.AllAuthority = res.data
    },
    //保存角色设置
    async saveRole(){
      let checkID = []
      for(let i = 0; i < this.AllAuthority.length; i++){
        let tag = false
        if(this.AllAuthority[i].children){
          for(let j = 0; j < this.AllAuthority[i].children.length; j++){
            if(this.AllAuthority[i].children[j].checked){
              tag = true
              checkID.push(this.AllAuthority[i].children[j].id)
            }
          }
        }
        if(tag){
          checkID.push(this.AllAuthority[i].id)
        }
      }
      this.roleInfo.authorities = checkID
      //先检验表单规则
      this.$refs.addForm.validate(async (valid) => {
        if(valid){
          const {data:res} = await this.$axios.post('/role/add', this.roleInfo)
          if(res.status == 200){
            this.$Message.info('添加成功');
            this.$router.push('/admin/role')
          }else{
            this.$Message.info('添加失败');
          } 
        }
      })      
    }
  }
}
</script>

<style>
  #addRole{
    margin:0 2vw;
  }
  h3{
    margin:1vh 0;
  }
  .node{
    margin-bottom:12px;
  }
  .children{
    margin-left:18px;
  }
  .ivu-form{
    width:40vw !important
  }
</style>